<template>
  <base-modal :title="$t('common.base.editEvaluated')" :show.sync="visible" width="700px" class="modify-evaluate-dialog" @close="close">
    <div class="base-modal-content">
      <el-form label-position="top" :model="form" ref="evaluteFormRef" v-if="!customerSatisfaction">
        <el-form-item :label="$t('task.detail.components.serviceDegree')">
          <label class="degree-item" v-for="item in degreeOption" :key="item">
            <input type="radio" class="hidden" name="degree" :value="item" v-model="form.degree"/>
            <!-- <span :class="['evaluate-degree-img', getDegreeImg(item, form.degree == item)]"></span> -->
            <i class="iconfont" :class="getDegreeImg(item, form.degree == item)"></i>
            <span class="degree-text">{{ item }}</span>
          </label>
        </el-form-item>
        <el-form-item :label="$t('task.detail.components.serviceEvaluate')" v-if="evaluateConfig.useStarEvaluate && starEvaluates.length">
          <div class="star-evaluate-row" v-for="(name, index) in starEvaluates" :key="index">
            <div class="star-title">{{ name }}</div>
            <base-service-star :value="starValue[starFields[index]]" @input="marks(starFields[index], $event)" :handle="true"></base-service-star>
          </div>
        </el-form-item>
        <el-form-item :label="$t('common.customer.questionnaire.serviceTag')" v-if="evaluateConfig.useTagEvaluate && tagEvaluates.length">
          <label class="tag-item" v-for="name in tagEvaluates" :key="name">
            <input type="checkbox" class="hidden" :value="name" v-model="tagValue">
            <span class="evaliate-tag-item">{{ name }}</span>
          </label>
        </el-form-item>

        <el-form-item :label="$t('event.setting.constant.flow_map.name5')">
          <el-input type="textarea" v-model="form.suggestion" maxlength="500" disabled></el-input>
        </el-form-item>
      </el-form>

      <div class="detail-evaluated" v-loading="showLoading" v-else>
        <iframe id="iframepage" ref="iframePage" :src="iframeUrl" height="350px" width="100%"/>
      </div>
    </div>
    <div slot="footer">
      <el-button @click="close">{{$t('common.base.close')}}</el-button>
      <el-button type="primary" @click="confirm2ModifyEvalute" :disabled="loading">{{$t('common.base.editEvaluated')}}</el-button>
    </div>
  </base-modal>
</template>

<script>
/* api */
import * as EventApi from '@src/api/EventApi.js';
import * as CustomerApi from '@src/api/CustomerApi.ts';
/* util */
import { getRootWindowInitData } from '@src/util/window';
const rootWindowInitData = getRootWindowInitData();

export default {
  name: 'modify-evaluate-dialog',
  props: {
    workEvent: {
      type: Object,
      default: () => {}
    },
    evaluateConfig: {
      type: Object,
      default: () => {}
    },
    evaluateData: {
      type: Object,
      default: () => {}
    }
  },
  computed: {
    starEvaluates(){
      return this.evaluateConfig.starEvaluates || [];
    },
    starFields(){
      return this.evaluateConfig.starEvaluateFeilds || [];
    },
    tagEvaluates(){
      return this.evaluateConfig.tagEvaluates || [];
    },
    // 展示回访问卷方案设置
    customerSatisfaction() {
      return rootWindowInitData?.customerSatisfaction;
    }
  },
  data() {
    return {
      degreeOption: [
        this.$t('common.base.satisfactionDegree.0'),
        this.$t('common.base.satisfactionDegree.1'),
        this.$t('common.base.satisfactionDegree.2'),
        this.$t('common.base.satisfactionDegree.3'),
        this.$t('common.base.satisfactionDegree.4')
      ],
      // degreeOption: ['满意', '一般', '不满意'],
      evaluateContent: '',
      visible: false,
      loading: false,
      form: {},
      starValue: {}, // 选择的服务评价
      tagValue: [], // 选择的服务标签
      iframeUrl: '',
      showLoading: false,
    }
  },
  mounted() {
    window.addEventListener('message', ({ data }) => {
      this.showLoading = data.showLoading;

      if (data.ret && data.id) {
        this.handleNewEvalute(data);
      }
    });
  },
  methods: {
    openDialog() {
      if (this.customerSatisfaction) {
        this.visible = true;
        this.showLoading = true;
        this.iframeUrl = `/pcoperation/satisfaction?type=EVENT&dataId=${this.workEvent.id}&typeId=${this.workEvent.templateId}`;
        return;
      }

      const { degree, suggestion, evaluateContent, evaluate } = this.workEvent
      this.form = Object.assign(this.evaluateData, { degree, suggestion, evaluate })
      this.evaluateContent = evaluateContent

      // 服务评价
      if(this.evaluateConfig.useStarEvaluate && this.starEvaluates.length) {
        this.starEvaluates.forEach((item, i) => {
          let value = this.form.evaluate[this.starFields[i]];
          this.$set(this.starValue, this.starFields[i], value || 0);
        })
      }
      // 服务标签回显
      if(this.evaluateConfig.useTagEvaluate && this.tagEvaluates.length){
        this.tagValue = this.evaluateData?.evaluateObj?.tagEvaluates || [];
      }
      this.visible = true
    },

    marks(field, value){
      this.$set(this.starValue, field, value);
    },

    getDegreeImg(type, selected) {
		  // if (type === '满意') {
      //   return selected ? 'review-degree-satisfy-active' : 'review-degree-satisfy';
      // }
      // if (type === '一般') {
      //   return selected ? 'review-degree-commonly-active' : 'review-degree-commonly';
      // }
      // if (type === '不满意') {
      //   return selected ? 'review-degree-unsatisfy-active' : 'review-degree-unsatisfy';
      // }
      let className = '';
      switch(type) {
        case this.$t('common.base.satisfactionDegree.0'): {
          className = selected ? 'icon-feichangmanyi verySatisfied' : 'icon-feichangmanyi';
          break;
        }
        case this.$t('common.base.satisfactionDegree.1'): {
          className = selected ? 'icon-manyi satisfied' : 'icon-manyi';
          break;
        }
        case this.$t('common.base.satisfactionDegree.2'): {
          className =  selected ? 'icon-yiban commonly' : 'icon-yiban';
          break;
        }
        case this.$t('common.base.satisfactionDegree.3'): {
          className =  selected ? 'icon-bumanyi disSatisfied' : 'icon-bumanyi';
          break;
        }
        case this.$t('common.base.satisfactionDegree.4'): {
          className =  selected ? 'icon-feichangbumanyi veryDissatisfied' : 'icon-feichangbumanyi';
          break;
        }
        default: {
          className = selected ? 'icon-feichangmanyi verySatisfied' : 'icon-feichangmanyi';
          break;
        }
      }
      return className;
    },
    
    getStar(fieldName) {
      let evaluate = this.form.evaluate || {};
      return evaluate[fieldName] || 0;
    },

    close() {
      this.visible = false;
      this.showLoading = false;
      this.iframeUrl = '';
    },

    handleNewEvalute({ id, ret }) {
      this.$confirm(this.$t('event.detail.components.dialog.text16'), this.$t('common.base.toast'), {
        confirmButtonText: this.$t('common.base.makeSure'),
        cancelButtonText: this.$t('common.base.cancel'),
        type: 'warning',
      })
        .then(() => {
          this.loading = true;

          CustomerApi.updateAnswer({
            triggerPointType: 'EVENT',
            triggerPointDataId: this.workEvent.id,
            satisfactionId: id,
            answers: ret
          })
            .then(res => {
              if (res.success) {
                this.$notify({title: this.$t('common.base.success'), message: this.$t('common.base.tip.editSuccess'), type: 'success'});
                setTimeout(() => {
                  this.visible = false
                  window.location.reload();
                }, 1000)
              } else {
                this.$platform.alert(res.message);
                this.loading = false;
              }
            })
            .catch(err => console.error(err))
        })
        .catch(err => console.error(err))
    },

    confirm2ModifyEvalute() {
      // 新版客户评价
      if (this.customerSatisfaction) {
        return this.$refs.iframePage.contentWindow.postMessage({ type: 'submit' }, '*');
      }

      this.$confirm(this.$t('event.detail.components.dialog.text16'), this.$t('common.base.toast'), {
        confirmButtonText: this.$t('common.base.makeSure'),
        cancelButtonText: this.$t('common.base.cancel'),
        type: 'warning',
      })
        .then(() => {
          let { useStarEvaluate, starEvaluateNotNull } = this.evaluateConfig;

          // 服务评星必填校验
          if(useStarEvaluate && starEvaluateNotNull){
            let message = [];
            for(let i = 0; i < this.starEvaluates.length; i++) {
              let name = this.starEvaluates[i];
              if(!this.starValue[this.starFeilds[i]]) {
                message.push(this.$t('task.tip.feedbackTip2', {name}));
              }
            }

            // 允许修改客户评价时
            if(message.length > 0) return this.$platform.alert(message.join('\n'));
          }

          this.loading = true;
          const params = {
            id: this.workEvent.id,
            degree: this.form.degree,
            suggestion: this.form.suggestion,
            evaluate: Object.assign(this.workEvent, {
              tagEvaluates: this.tagValue,
              ...this.starValue
            })
          }
          console.log('params', params)
          EventApi.eventEvaluateUpdate(params)
            .then(res => {
              if(res.status == 0){
                this.$notify({
                  title: this.$t('common.base.success'),
                  message: this.$t('common.base.tip.editSuccess'),
                  type: 'success'
                });
                setTimeout(() => {
                  this.visible = false
                  window.location.reload();
                }, 1000)
              }else{
                this.loading = false;
                this.$notify({
                  title: this.$t('common.base.error'),
                  message: res.message,
                  type: 'error'
                });
              }
            })
            .catch(err => {console.error(err)})
        })
        .catch(() => { });
    }
  }
}
</script>

<style lang="scss" scoped>

.evaluate-degree-img {
  width: 24px;
  height: 24px;
  margin-right: 2px;
  display: inline-block;
  vertical-align: middle;

  background: url(../../../../../assets/img/task/review-degree.png) no-repeat;
  background-size: 24px 144px;

  &.review-degree-satisfy {
    background-position: 0 0;
  }

  &.review-degree-commonly {
    background-position: 0 -24px;
  }

  &.review-degree-unsatisfy {
    background-position: 0 -48px;
  }

  &.review-degree-satisfy-active {
    background-position: 0 -72px;
  }

  &.review-degree-commonly-active {
    background-position: 0 -96px;
  }

  &.review-degree-unsatisfy-active {
    background-position: 0 -120px;
  }
}
.base-modal-content {
  padding: 20px;
  .degree-item {
    margin-right: 16px;
    cursor: pointer;
    .icon-feichangmanyi,.icon-manyi,.icon-yiban,.icon-bumanyi,.icon-feichangbumanyi{
      color:#595959!important;
      font-size:24px;
      width: 24px;
      height: 24px;
      line-height: 24px;
      margin-right: 2px;
      display: inline-block;
      vertical-align: middle;
    }
    .verySatisfied{
      color: #52c41a!important;
    }
    .satisfied {
      color: #26c8ff!important;
    }
    .commonly {
      color: #ffa726!important;
    }
    .disSatisfied {
      color: #ff7043!important;
    }
    .veryDissatisfied {
      color: #d9363e!important;
    }
  }

  .star-evaluate-row {
    display: flex;
    margin-bottom: 10px;
    .star-title {
        width: 86px;
        margin-right: 6px;
    }
  }

  .tag-item {
    .evaliate-tag-item {
      display: inline-block;
      padding: 2px 8px;
      margin: 0 10px 10px 0;
      font-size: 12px;
      border: 1px solid #e5e5e5;
      background-color: #f8f7f6;
      border-radius: 2px;
      color: #757575;
      cursor: pointer;
      line-height: initial;
    }

    .evaliate-tag-active,
    input[type='checkbox']:checked ~ span {
      color: #00d1d3;
      background-color: #f5fffd;
      border-color: #00d1d3;
    }
  }
}
</style>